package com.git.smp.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections4.MultiValuedMap;
import org.apache.xmlbeans.impl.common.SystemCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import com.git.smp.cache.DataDictionaryCache;
import com.git.smp.cache.SmpSystemCache;
import com.git.smp.cache.SmpUserCache;
import com.git.smp.dao.EsbEnvironmentMapper;
import com.git.smp.dao.RequirementBatchAnnexMapper;
import com.git.smp.dao.RequirementBatchMapper;
import com.git.smp.dao.RequirementBatchTiemMapper;
import com.git.smp.dao.RequirementInfoMapper;
import com.git.smp.dao.SmpSystemCallMapper;
import com.git.smp.entity.CallListInfo;
import com.git.smp.entity.DocumentRequest;
import com.git.smp.entity.MappingNameInfo;
import com.git.smp.entity.RequirementBatch;
import com.git.smp.entity.RequirementBatchAnnex;
import com.git.smp.entity.RequirementBatchTiem;
import com.git.smp.entity.RequirementInfo;
import com.git.smp.entity.SmpSystemCall;
import com.git.smp.entitydoc.CallInfo;
import com.git.smp.entitydoc.ConfigFile;
import com.git.smp.entitydoc.InterfaceInfo;
import com.git.smp.entitydoc.ReqInfo;
import com.git.smp.utils.InitSql;
import com.git.smp.utils.ReqUtil;
import com.git.smp.utils.StringUtil;

import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateNotFoundException;

@RestController
@RequestMapping("/document")
public class ExportDocumentController {

	public static final String KEY_reqNo = "reqNo";
	public static final String KEY_reqName = "reqName";
	public static final String KEY_esbReqNo = "esbReqNo";
	public static final String KEY_reqFullName = "reqFullName";
	public static final String KEY_revisionDate = "revisionDate";
	public static final String KEY_evaluateDate = "evaluateDate";
	public static final String KEY_pubDate = "pubDate";
	public static final String KEY_reviewer = "reviewer";
	public static final String KEY_initTestVersion = "initTestVersion";
	public static final String KEY_verifyTestVersionList = "verifyTestVersionList";
	public static final String KEY_passTestVersion = "passTestVersion";
	public static final String KEY_testCycle = "testCycle";
	public static final String KEY_tester = "tester";
	public static final String KEY_interfaceList = "interfaceList";
	public static final String KEY_images = "images";
	public static final String KEY_testOverview = "testOverview";
	public static final String KEY_testRange = "testRange";
	public static final String KEY_callList = "callList";
	public static final String KEY_bizDesc = "bizDesc";
	public static final String KEY_designDesc = "designDesc";
	public static final String KEY_sqlFile = "sqlFile";
	public static final String KEY_mappingFiles = "mappingFiles";
	public static final String KEY_sbconfigFile = "sbconfigFile";
	public static final String KEY_hostConfig = "hostConfig";

	Logger logger = LoggerFactory.getLogger(ExportDocumentController.class);

	@Autowired
	private HttpServletResponse response;

	@Autowired
	private Configuration configuration;

	@Autowired
	EsbEnvironmentMapper environmentMapper;

	@Autowired
	RequirementBatchMapper batchMapper;

	@Autowired
	SmpSystemCallMapper smpSystemCallMapper;

	@Autowired
	RequirementInfoMapper requirementInfoMapper;

	@Autowired
	RequirementBatchMapper requirementBatchMapper;

	@Autowired
	RequirementBatchTiemMapper requirementBatchTiemMapper;

	@Autowired
	RequirementBatchAnnexMapper requirementBatchAnnexMapper;

	@Autowired
	RestTemplate restTemplate;

	/**
	 * 
	 * @param files
	 * @param esbQmsNo
	 * @param esbQmsName
	 * @param oesbQmsNo
	 * @param oesbQmsName
	 * @param qmsNo
	 * @param hostConfig
	 * @param docType
	 * @param batchNum
	 * @param evaluateDate
	 * @param pubDate
	 * @param reviewer
	 * @param testCycle
	 * @param checkUser
	 * @throws TemplateNotFoundException
	 * @throws MalformedTemplateNameException
	 * @throws ParseException
	 * @throws IOException
	 * @throws java.text.ParseException
	 */
	@RequestMapping("/exportDocumentold")
	public void exportDocumentold(MultipartFile[] files, String esbQmsNo, String esbQmsName, String oesbQmsNo,
			String oesbQmsName, String qmsNo, String hostConfig, String docType, String batchNum, String evaluateDate,
			String pubDate, String testCycle, String[] fileNameList) throws TemplateNotFoundException,
			MalformedTemplateNameException, ParseException, IOException, java.text.ParseException {

		RequirementBatch requirementBatch = new RequirementBatch();
		requirementBatch.setQmsNo(qmsNo);
		requirementBatch.setBatchNum(batchNum);

		// 信息补录
		requirementBatch.setEsbQmsNo(esbQmsNo);
		requirementBatch.setEsbQmsName(esbQmsName);
		requirementBatch.setEvaluateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(evaluateDate));
		requirementBatch.setPubDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(pubDate));
		requirementBatch.setTestCycle(testCycle);
		requirementBatch.setEsbHostConfig(hostConfig);
		requirementBatchMapper.updateByPrimaryKeySelective(requirementBatch);

		// 添加，修改附件
		RequirementBatchAnnex requirementBatchAnnex = new RequirementBatchAnnex();
		requirementBatchAnnex.setQmsNo(qmsNo);
		requirementBatchAnnex.setBatchNum(batchNum);
		requirementBatchAnnex.setCreateDate(new Date());

		// 删除不在fileList的附件
		if (fileNameList != null && fileNameList.length > 0) {
			requirementBatchAnnexMapper.deleteExcludeFileNames(qmsNo, batchNum, fileNameList);
		}

		try {

			for (MultipartFile file : files) {
				requirementBatchAnnex.setFileName(file.getOriginalFilename());
				requirementBatchAnnex.setFileContent(file.getBytes());

				requirementBatchAnnexMapper.insertSelective(requirementBatchAnnex);
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		evaluateDate = new SimpleDateFormat("yyyy/M/d")
				.format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(evaluateDate));

		RequirementBatch requirementBatch1 = batchMapper.selectByPrimaryKey(requirementBatch);

		RequirementInfo requirementInfo = requirementInfoMapper.selectByPrimaryKey(requirementBatch.getQmsNo());

		String REVISION_DATE = new SimpleDateFormat("yyyyMMdd").format(new Date());

		response.setContentType("application/octet-stream;charset=UTF-8");

		OutputStream out = null;
		ZipOutputStream zip = null;

		hostConfig = StringUtil.isBlank(hostConfig) ? "无" : hostConfig;

		try {
			out = response.getOutputStream();
			zip = new ZipOutputStream(out);

		} catch (Exception e) {
			e.printStackTrace();
		}

		RequirementBatchTiem requirementBatchTiem = new RequirementBatchTiem();
		requirementBatchTiem.setBatchNum(requirementBatch.getBatchNum());
		requirementBatchTiem.setQmsNo(requirementBatch.getQmsNo());
		List<RequirementBatchTiem> RequirementBatchTiemList = requirementBatchTiemMapper
				.selectByQmsNoAndesbRelaseNotNull(requirementBatchTiem);
		List<String> testVersionList = new ArrayList<String>();
		if (RequirementBatchTiemList != null && RequirementBatchTiemList.size() > 0) {
			RequirementBatchTiemList.forEach(obj -> {
				testVersionList.add(obj.getEsbRelase());
			});
		}

		List<InterfaceInfo> interfaceList = new ArrayList<>();
		// 调用列表
		SmpSystemCall smpSystemCall = new SmpSystemCall();
		smpSystemCall.setBatchNum(requirementBatch.getBatchNum());
		smpSystemCall.setAssociatedRequirement(requirementBatch.getQmsNo());

		Map<String, List<InterfaceInfo>> callMap = new HashMap<>();

		List<CallListInfo> listConsumeInfo = smpSystemCallMapper.getConsumeInfoByQmsNo(smpSystemCall);
		if (listConsumeInfo != null && listConsumeInfo.size() > 0) {
			listConsumeInfo.forEach(callListInfo -> {
				InterfaceInfo interfaceInfo = new InterfaceInfo(callListInfo.getTransCode(),
						callListInfo.getTransName());

				if (!interfaceList.contains(interfaceInfo)) {
					interfaceList.add(interfaceInfo);
				}

				List<InterfaceInfo> InterfaceInfos = callMap
						.get(callListInfo.getRegSysCode() + "|" + callListInfo.getSystemNo());
				if (InterfaceInfos != null) {
					InterfaceInfos.add(interfaceInfo);
				} else {
					List<InterfaceInfo> InterfaceInfos1 = new ArrayList<>();
					InterfaceInfos1.add(interfaceInfo);
					callMap.put(callListInfo.getRegSysCode() + "|" + callListInfo.getSystemNo(), InterfaceInfos1);
				}

			});
		}

		List<CallInfo> callInfos = new ArrayList<>();
		callMap.forEach((key, value) -> {
			String[] reg_pub = key.split("\\|");

			callInfos.add(new CallInfo(SmpSystemCache.getSystemName(reg_pub[0]), value,
					SmpSystemCache.getSystemName(reg_pub[1])));
		});

		List<String> mappingFiles = new ArrayList<>();
		// 列举所有mappingFile
		/*
		 * SmpSystemCall smpSystemCall = new SmpSystemCall();
		 * smpSystemCall.setAssociatedRequirement(requirementBatch.getQmsNo());
		 * smpSystemCall.setBatchNum(requirementBatch.getBatchNum());
		 */
		List<MappingNameInfo> listMappingNameInfo = smpSystemCallMapper.getMappingNameInfoList(smpSystemCall);
		if (listMappingNameInfo != null) {
			listMappingNameInfo.forEach(mappingNameInfo -> {
				mappingFiles.add(mappingNameInfo.getSystemShort() + "_" + mappingNameInfo.getPubCode() + ".xml");
			});
		}

		List<String> images = new ArrayList<>();

		// 查询附件
		List<RequirementBatchAnnex> annexList = requirementBatchAnnexMapper.selectByPrimaryKey(requirementBatchAnnex);
		for (RequirementBatchAnnex requirementBatchAnnex2 : annexList) {
			images.add(Base64.getEncoder().encodeToString(requirementBatchAnnex2.getFileContent()));
		}

//		for(int i = 0;i<files.length;i++) {
//			images.add(getImg(files[i]));
//		}

		ConfigFile configFile = new ConfigFile(requirementBatch1.getQmsNo() + "_ESB.sql", "sbconfig.jar");
		configFile.setMappingFiles(mappingFiles);

		ReqInfo reqInfo = new ReqInfo.Builder().reqNo(requirementBatch1.getQmsNo())
				.reqName(requirementInfo.getQmsName()).reqFullName(esbQmsName).revisionDate(REVISION_DATE)
				.evaluateDate(evaluateDate).pubDate(pubDate)
				.reviewer(SmpUserCache.getSmpUserName(requirementBatch1.getDealUser())).testVersionList(testVersionList)
				.tester(SmpUserCache.getSmpUserName(requirementBatch1.getDealUser())).testCycle(testCycle)
				.batchNo(DataDictionaryCache.getItemName("SMP0010", requirementBatch1.getBatchNum()))
				.interfaceList(interfaceList).screenshots(images).callInfos(callInfos).configFile(configFile)
				.hostConfig(hostConfig).esbReqNo(esbQmsNo).build();

		Map<String, Object> params = new HashMap<>();
		params.put(KEY_esbReqNo, reqInfo.getEsbReqNo());
		params.put(KEY_reqName, reqInfo.getReqName());
		params.put(KEY_reqFullName, reqInfo.getReqFullName());
		params.put(KEY_revisionDate, reqInfo.getRevisionDate());
		params.put(KEY_pubDate, new SimpleDateFormat("yyyyMMdd")
				.format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(reqInfo.getPubDate())));
		params.put(KEY_reviewer, reqInfo.getReviewer());
		params.put(KEY_passTestVersion, ReqUtil.getPassTestVersion(reqInfo));
		params.put(KEY_sqlFile, reqInfo.getConfigFile().getSqlFile());
		params.put(KEY_hostConfig, reqInfo.getHostConfig());

		ZipEntry zipEntry = new ZipEntry(reqInfo.getEsbReqNo() + "_" + reqInfo.getReqFullName() + "_安装部署手册.doc");
		Template template = configuration.getTemplate("anzhuangbushushouce_ESB.ftl");
		try {
			zip.putNextEntry(zipEntry);
			Writer writer = new OutputStreamWriter(zip);
			template.process(params, writer);
			zip.closeEntry();
		} catch (Exception e) {
			e.printStackTrace();
		}

		/* params = new HashMap<>(); */
		params = new HashMap<>();
		params.put(KEY_esbReqNo, reqInfo.getEsbReqNo());
		params.put(KEY_reqNo, reqInfo.getReqNo());
		params.put(KEY_reqName, reqInfo.getReqName());
		params.put(KEY_reqFullName, reqInfo.getReqFullName());
		params.put(KEY_revisionDate, reqInfo.getRevisionDate());
		params.put(KEY_reviewer, reqInfo.getReviewer());
		params.put(KEY_sqlFile, reqInfo.getConfigFile().getSqlFile());
		params.put(KEY_mappingFiles, reqInfo.getConfigFile().getMappingFiles());
		params.put(KEY_sbconfigFile, reqInfo.getConfigFile().getSbconfigFile());
		params.put(KEY_hostConfig, reqInfo.getHostConfig());

		zipEntry = new ZipEntry(reqInfo.getEsbReqNo() + "_" + reqInfo.getReqFullName() + "_改造类发布方案.doc");
		template = configuration.getTemplate("gaizaoleifabu_ESB.ftl");
		try {
			zip.putNextEntry(zipEntry);
			Writer writer = new OutputStreamWriter(zip);
			template.process(params, writer);
			zip.closeEntry();
		} catch (Exception e) {
			e.printStackTrace();
		}

		/* params = new HashMap<>(); */
		params = new HashMap<>();
		params.put(KEY_esbReqNo, reqInfo.getEsbReqNo());
		params.put(KEY_reqNo, reqInfo.getReqNo());
		params.put(KEY_reqName, reqInfo.getReqName());
		params.put(KEY_reqFullName, reqInfo.getReqFullName());
		params.put(KEY_revisionDate, reqInfo.getRevisionDate());
		params.put(KEY_reviewer, reqInfo.getReviewer());
		params.put(KEY_passTestVersion, ReqUtil.getPassTestVersion(reqInfo));
		params.put(KEY_testOverview, ReqUtil.getTestOverview(reqInfo));
		params.put(KEY_callList, reqInfo.getCallInfos());
		params.put(KEY_bizDesc, ReqUtil.getBizDesc(reqInfo));
		params.put(KEY_designDesc, ReqUtil.getDesignDesc(reqInfo));

		zipEntry = new ZipEntry(reqInfo.getEsbReqNo() + "_" + reqInfo.getReqFullName() + "_改造类设计说明书.doc");
		template = configuration.getTemplate("gaizaoleisheji_ESB.ftl");
		try {
			zip.putNextEntry(zipEntry);
			Writer writer = new OutputStreamWriter(zip);
			template.process(params, writer);
			zip.closeEntry();
		} catch (Exception e) {
			e.printStackTrace();
		}

		params = new HashMap<>();
		params.put(KEY_esbReqNo, reqInfo.getEsbReqNo());
		params.put(KEY_reqNo, reqInfo.getReqNo());
		params.put(KEY_reqName, reqInfo.getReqName());
		params.put(KEY_reqFullName, reqInfo.getReqFullName());
		params.put(KEY_evaluateDate, reqInfo.getEvaluateDate());
		params.put(KEY_reviewer, reqInfo.getReviewer());
		params.put(KEY_interfaceList, reqInfo.getInterfaceList());

		zipEntry = new ZipEntry(reqInfo.getEsbReqNo() + "_" + reqInfo.getReqFullName() + "_改造类需求估算表.xlsx");
		template = configuration.getTemplate("gusuanbiao_ESB.ftl");
		try {
			zip.putNextEntry(zipEntry);
			Writer writer = new OutputStreamWriter(zip);
			template.process(params, writer);
			zip.closeEntry();
		} catch (Exception e) {
			e.printStackTrace();
		}

		params.put(KEY_esbReqNo, reqInfo.getEsbReqNo());
		params.put(KEY_reqNo, reqInfo.getReqNo());
		params.put(KEY_reqName, reqInfo.getReqName());
		params.put(KEY_reqFullName, reqInfo.getReqFullName());
		params.put(KEY_revisionDate, reqInfo.getRevisionDate());
		params.put(KEY_reviewer, reqInfo.getReviewer());
		params.put(KEY_initTestVersion, ReqUtil.getInitTestVersion(reqInfo));
		params.put(KEY_verifyTestVersionList, ReqUtil.getVerifyTestVersionList(reqInfo));
		params.put(KEY_passTestVersion, ReqUtil.getPassTestVersion(reqInfo));
		params.put(KEY_sqlFile, reqInfo.getConfigFile().getSqlFile());

		params.put(KEY_testCycle, reqInfo.getTestCycle());
		params.put(KEY_tester, reqInfo.getTester());
		params.put(KEY_interfaceList, reqInfo.getInterfaceList());
		params.put(KEY_images, reqInfo.getScreenshots());
		params.put(KEY_testOverview, ReqUtil.getTestOverview(reqInfo));
		params.put(KEY_testRange, ReqUtil.getTestRange(reqInfo));

		zipEntry = new ZipEntry(reqInfo.getEsbReqNo() + "_" + reqInfo.getReqFullName() + "_改造类技术测试报告.doc");
		template = configuration.getTemplate("ceshibaogao_ESB.ftl");
		try {
			zip.putNextEntry(zipEntry);
			Writer writer = new OutputStreamWriter(zip);
			template.process(params, writer);
			zip.closeEntry();
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			zip.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			out.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		logger.info("生成文件成功！");
	}

	/**
	 * 
	 * @param files
	 * @param esbQmsNo
	 * @param esbQmsName
	 * @param oesbQmsNo
	 * @param oesbQmsName
	 * @param qmsNo
	 * @param hostConfig
	 * @param docType
	 * @param batchNum
	 * @param evaluateDate
	 * @param pubDate
	 * @param reviewer
	 * @param testCycle
	 * @param checkUser
	 * @throws TemplateNotFoundException
	 * @throws MalformedTemplateNameException
	 * @throws ParseException
	 * @throws IOException
	 * @throws java.text.ParseException
	 */
	@RequestMapping("/exportDocument")
	public void exportDocument(MultipartFile[] files, String esbQmsNo, String esbQmsName, String oesbQmsNo,
			String oesbQmsName, String qmsNo, String hostConfig, String docType, String batchNum, String evaluateDate,
			String pubDate, String testCycle, String[] fileNameList) throws TemplateNotFoundException,
			MalformedTemplateNameException, ParseException, IOException, java.text.ParseException {

		RequirementBatch requirementBatch = new RequirementBatch();
		requirementBatch.setQmsNo(qmsNo);
		requirementBatch.setBatchNum(batchNum);

		// 信息补录
		requirementBatch.setEsbQmsNo(esbQmsNo);
		requirementBatch.setEsbQmsName(esbQmsName);
		requirementBatch.setEvaluateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(evaluateDate));
		requirementBatch.setPubDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(pubDate));
		requirementBatch.setTestCycle(testCycle);
		requirementBatch.setEsbHostConfig(hostConfig);
		requirementBatchMapper.updateByPrimaryKeySelective(requirementBatch);

		// 添加，修改附件
		RequirementBatchAnnex requirementBatchAnnex = new RequirementBatchAnnex();
		requirementBatchAnnex.setQmsNo(qmsNo);
		requirementBatchAnnex.setBatchNum(batchNum);
		requirementBatchAnnex.setCreateDate(new Date());

		// 删除不在fileList的附件
		if (fileNameList != null && fileNameList.length > 0) {
			requirementBatchAnnexMapper.deleteExcludeFileNames(qmsNo, batchNum, fileNameList);
		}

		try {

			for (MultipartFile file : files) {
				requirementBatchAnnex.setFileName(file.getOriginalFilename());
				requirementBatchAnnex.setFileContent(file.getBytes());

				requirementBatchAnnexMapper.insertSelective(requirementBatchAnnex);
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		DocumentRequest body = new DocumentRequest();
		body.setQmsNo(qmsNo);
		body.setBatchNum(batchNum);

		ResponseEntity<byte[]> responseEnity = restTemplate
				.postForEntity("http://10.0.91.157:11111/exportDocument", body, byte[].class);
		response.setContentType("application/octet-stream;charset=UTF-8");
		OutputStream out = null;
		out = response.getOutputStream();
		out.write(responseEnity.getBody());
		try {
			out.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		logger.info("生成文件成功！");
	}

	/**
	 * 
	 * @param files
	 * @param esbQmsNo
	 * @param esbQmsName
	 * @param oesbQmsNo
	 * @param oesbQmsName
	 * @param qmsNo
	 * @param hostConfig
	 * @param docType
	 * @param batchNum
	 * @param evaluateDate
	 * @param pubDate
	 * @param reviewer
	 * @param testCycle
	 * @param checkUser
	 * @throws TemplateNotFoundException
	 * @throws MalformedTemplateNameException
	 * @throws ParseException
	 * @throws IOException
	 * @throws java.text.ParseException
	 */
	@RequestMapping("/exportOesbDocument")
	public void exportOesbDocument(MultipartFile[] files, String oesbQmsNo, String oesbQmsName, String qmsNo,
			String hostConfig, String docType, String batchNum, String evaluateDate, String pubDate, String testCycle,
			String[] fileNameList) throws TemplateNotFoundException, MalformedTemplateNameException, ParseException,
			IOException, java.text.ParseException {

		RequirementBatch requirementBatch = new RequirementBatch();
		requirementBatch.setQmsNo(qmsNo);
		requirementBatch.setBatchNum(batchNum);

		// 信息补录
		requirementBatch.setOesbQmsNo(oesbQmsNo);
		requirementBatch.setOesbQmsName(oesbQmsName);
		requirementBatch.setEvaluateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(evaluateDate));
		requirementBatch.setPubDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(pubDate));
		requirementBatch.setTestCycle(testCycle);
		requirementBatch.setOesbHostConfig(hostConfig);
		requirementBatchMapper.updateByPrimaryKeySelective(requirementBatch);

		// 添加，修改附件
		RequirementBatchAnnex requirementBatchAnnex = new RequirementBatchAnnex();
		requirementBatchAnnex.setQmsNo(qmsNo);
		requirementBatchAnnex.setBatchNum(batchNum);
		requirementBatchAnnex.setCreateDate(new Date());

		// 删除不在fileList的附件
		if (fileNameList != null && fileNameList.length > 0) {
			requirementBatchAnnexMapper.deleteExcludeFileNames(qmsNo, batchNum, fileNameList);
		}

		try {

			for (MultipartFile file : files) {
				requirementBatchAnnex.setFileName(file.getOriginalFilename());
				requirementBatchAnnex.setFileContent(file.getBytes());

				requirementBatchAnnexMapper.insertSelective(requirementBatchAnnex);
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		response.setContentType("application/octet-stream;charset=UTF-8");

		DocumentRequest body = new DocumentRequest();
		body.setQmsNo(qmsNo);
		body.setBatchNum(batchNum);

		ResponseEntity<byte[]> responseEnity = restTemplate
				.postForEntity("http://10.0.91.157:11111/exportDocument_OESB", body, byte[].class);

		response.setContentType("application/octet-stream;charset=UTF-8");
		OutputStream out = null;

		try {
			out = response.getOutputStream();

		} catch (Exception e) {
			e.printStackTrace();
		}
		out.write(responseEnity.getBody());

		try {
			out.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		logger.info("生成文件成功！");
	}

	/**
	 * 
	 * @param files
	 * @param esbQmsNo
	 * @param esbQmsName
	 * @param oesbQmsNo
	 * @param oesbQmsName
	 * @param qmsNo
	 * @param hostConfig
	 * @param docType
	 * @param batchNum
	 * @param evaluateDate
	 * @param pubDate
	 * @param reviewer
	 * @param testCycle
	 * @param checkUser
	 * @throws TemplateNotFoundException
	 * @throws MalformedTemplateNameException
	 * @throws ParseException
	 * @throws IOException
	 * @throws java.text.ParseException
	 */
	@RequestMapping("/exportOesbDocumentold")
	public void exportOesbDocumentold(MultipartFile[] files, String oesbQmsNo, String oesbQmsName, String qmsNo,
			String hostConfig, String docType, String batchNum, String evaluateDate, String pubDate, String testCycle,
			String[] fileNameList) throws TemplateNotFoundException, MalformedTemplateNameException, ParseException,
			IOException, java.text.ParseException {

		RequirementBatch requirementBatch = new RequirementBatch();
		requirementBatch.setQmsNo(qmsNo);
		requirementBatch.setBatchNum(batchNum);

		// 信息补录
		requirementBatch.setOesbQmsNo(oesbQmsNo);
		requirementBatch.setOesbQmsName(oesbQmsName);
		requirementBatch.setEvaluateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(evaluateDate));
		requirementBatch.setPubDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(pubDate));
		requirementBatch.setTestCycle(testCycle);
		requirementBatch.setOesbHostConfig(hostConfig);
		requirementBatchMapper.updateByPrimaryKeySelective(requirementBatch);

		// 添加，修改附件
		RequirementBatchAnnex requirementBatchAnnex = new RequirementBatchAnnex();
		requirementBatchAnnex.setQmsNo(qmsNo);
		requirementBatchAnnex.setBatchNum(batchNum);
		requirementBatchAnnex.setCreateDate(new Date());

		// 删除不在fileList的附件
		if (fileNameList != null && fileNameList.length > 0) {
			requirementBatchAnnexMapper.deleteExcludeFileNames(qmsNo, batchNum, fileNameList);
		}

		try {

			for (MultipartFile file : files) {
				requirementBatchAnnex.setFileName(file.getOriginalFilename());
				requirementBatchAnnex.setFileContent(file.getBytes());

				requirementBatchAnnexMapper.insertSelective(requirementBatchAnnex);
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		evaluateDate = new SimpleDateFormat("yyyy/M/d")
				.format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(evaluateDate));

		hostConfig = StringUtil.isBlank(hostConfig) ? "无" : hostConfig;

		RequirementBatch requirementBatch1 = batchMapper.selectByPrimaryKey(requirementBatch);

		RequirementInfo requirementInfo = requirementInfoMapper.selectByPrimaryKey(requirementBatch.getQmsNo());

		String REVISION_DATE = new SimpleDateFormat("yyyyMMdd").format(new Date());

		response.setContentType("application/octet-stream;charset=UTF-8");

		OutputStream out = null;
		ZipOutputStream zip = null;

		try {
			out = response.getOutputStream();
			zip = new ZipOutputStream(out);

		} catch (Exception e) {
			e.printStackTrace();
		}

		RequirementBatchTiem requirementBatchTiem = new RequirementBatchTiem();
		requirementBatchTiem.setBatchNum(requirementBatch.getBatchNum());
		requirementBatchTiem.setQmsNo(requirementBatch.getQmsNo());
		List<RequirementBatchTiem> RequirementBatchTiemList = requirementBatchTiemMapper
				.selectByQmsNoAndoesbRelaseNotNull(requirementBatchTiem);
		List<String> testVersionList = new ArrayList<String>();
		if (RequirementBatchTiemList != null && RequirementBatchTiemList.size() > 0) {
			RequirementBatchTiemList.forEach(obj -> {
				testVersionList.add(obj.getOesbRelase());
			});
		}

		List<InterfaceInfo> interfaceList = new ArrayList<>();
		// 调用列表
		SmpSystemCall smpSystemCall = new SmpSystemCall();
		smpSystemCall.setBatchNum(requirementBatch.getBatchNum());
		smpSystemCall.setAssociatedRequirement(requirementBatch.getQmsNo());

		Map<String, List<InterfaceInfo>> callMap = new HashMap<>();

		List<CallListInfo> listConsumeInfo = smpSystemCallMapper.getConsumeInfoByQmsNo(smpSystemCall);
		if (listConsumeInfo != null && listConsumeInfo.size() > 0) {
			listConsumeInfo.forEach(callListInfo -> {

				if (callListInfo.getOesbLocalPath() != null && !"".equals(callListInfo.getOesbLocalPath())) {
					InterfaceInfo interfaceInfo = new InterfaceInfo(callListInfo.getTransCode(),
							callListInfo.getTransName());

					if (!interfaceList.contains(interfaceInfo)) {
						interfaceList.add(interfaceInfo);
					}

					List<InterfaceInfo> InterfaceInfos = callMap
							.get(callListInfo.getRegSysCode() + "|" + callListInfo.getSystemNo());
					if (InterfaceInfos != null) {
						InterfaceInfos.add(interfaceInfo);
					} else {
						List<InterfaceInfo> InterfaceInfos1 = new ArrayList<>();
						InterfaceInfos1.add(interfaceInfo);
						callMap.put(callListInfo.getRegSysCode() + "|" + callListInfo.getSystemNo(), InterfaceInfos1);
					}

				}

			});
		}

		List<CallInfo> callInfos = new ArrayList<>();
		callMap.forEach((key, value) -> {
			String[] reg_pub = key.split("\\|");

			callInfos.add(new CallInfo(SmpSystemCache.getSystemName(reg_pub[0]), value,
					SmpSystemCache.getSystemName(reg_pub[1])));
		});

		List<String> mappingFiles = new ArrayList<>();
		// 列举所有mappingFile
		/*
		 * SmpSystemCall smpSystemCall = new SmpSystemCall();
		 * smpSystemCall.setAssociatedRequirement(requirementBatch.getQmsNo());
		 * smpSystemCall.setBatchNum(requirementBatch.getBatchNum());
		 */

		/*
		 * List<MappingNameInfo> listMappingNameInfo =
		 * smpSystemCallMapper.getMappingNameInfoList(smpSystemCall); if
		 * (listMappingNameInfo != null) { listMappingNameInfo.forEach(mappingNameInfo
		 * -> { mappingFiles.add(mappingNameInfo.getSystemShort() + "_" +
		 * mappingNameInfo.getPubCode() + ".xml"); }); }
		 */

		List<String> images = new ArrayList<>();

		// 查询附件
		List<RequirementBatchAnnex> annexList = requirementBatchAnnexMapper.selectByPrimaryKey(requirementBatchAnnex);
		for (RequirementBatchAnnex requirementBatchAnnex2 : annexList) {
			images.add(Base64.getEncoder().encodeToString(requirementBatchAnnex2.getFileContent()));
		}
//		for(int i = 0;i<files.length;i++) {
//			images.add(getImg(files[i]));
//		}
		ConfigFile configFile = new ConfigFile(requirementBatch1.getQmsNo() + "_OESB.sql", "sbconfig.jar");
		configFile.setMappingFiles(mappingFiles);

		ReqInfo reqInfo = new ReqInfo.Builder().reqNo(requirementBatch1.getQmsNo())
				.reqName(requirementInfo.getQmsName()).reqFullName(oesbQmsName).revisionDate(REVISION_DATE)
				.evaluateDate(evaluateDate).pubDate(pubDate)
				.reviewer(SmpUserCache.getSmpUserName(requirementBatch1.getDealUser())).testVersionList(testVersionList)
				.tester(SmpUserCache.getSmpUserName(requirementBatch1.getDealUser())).testCycle(testCycle)
				.batchNo(DataDictionaryCache.getItemName("SMP0010", requirementBatch1.getBatchNum()))
				.interfaceList(interfaceList).screenshots(images).callInfos(callInfos).configFile(configFile)
				.hostConfig(hostConfig).esbReqNo(oesbQmsNo).build();

		Map<String, Object> params = new HashMap<>();
		params.put(KEY_esbReqNo, reqInfo.getEsbReqNo());
		params.put(KEY_reqName, reqInfo.getReqName());
		params.put(KEY_reqFullName, reqInfo.getReqFullName());
		params.put(KEY_revisionDate, reqInfo.getRevisionDate());
		params.put(KEY_pubDate, reqInfo.getPubDate());
		params.put(KEY_reviewer, reqInfo.getReviewer());
		params.put(KEY_passTestVersion, ReqUtil.getPassTestVersion(reqInfo));
		params.put(KEY_sqlFile, reqInfo.getConfigFile().getSqlFile());
		params.put(KEY_hostConfig, reqInfo.getHostConfig());

		ZipEntry zipEntry = new ZipEntry(reqInfo.getEsbReqNo() + "_" + reqInfo.getReqFullName() + "_安装部署手册.doc");
		Template template = configuration.getTemplate("anzhuangbushushouce_OESB.ftl");
		try {
			zip.putNextEntry(zipEntry);
			Writer writer = new OutputStreamWriter(zip);
			template.process(params, writer);
			zip.closeEntry();
		} catch (Exception e) {
			e.printStackTrace();
		}

		/* params = new HashMap<>(); */
		params = new HashMap<>();
		params.put(KEY_esbReqNo, reqInfo.getEsbReqNo());
		params.put(KEY_reqNo, reqInfo.getReqNo());
		params.put(KEY_reqName, reqInfo.getReqName());
		params.put(KEY_reqFullName, reqInfo.getReqFullName());
		params.put(KEY_revisionDate, reqInfo.getRevisionDate());
		params.put(KEY_reviewer, reqInfo.getReviewer());
		params.put(KEY_sqlFile, reqInfo.getConfigFile().getSqlFile());
		params.put(KEY_mappingFiles, reqInfo.getConfigFile().getMappingFiles());
		params.put(KEY_sbconfigFile, reqInfo.getConfigFile().getSbconfigFile());
		params.put(KEY_hostConfig, reqInfo.getHostConfig());

		zipEntry = new ZipEntry(reqInfo.getEsbReqNo() + "_" + reqInfo.getReqFullName() + "_改造类发布方案.doc");
		template = configuration.getTemplate("gaizaoleifabu_OESB.ftl");
		try {
			zip.putNextEntry(zipEntry);
			Writer writer = new OutputStreamWriter(zip);
			template.process(params, writer);
			zip.closeEntry();
		} catch (Exception e) {
			e.printStackTrace();
		}

		/* params = new HashMap<>(); */
		params = new HashMap<>();
		params.put(KEY_esbReqNo, reqInfo.getEsbReqNo());
		params.put(KEY_reqNo, reqInfo.getReqNo());
		params.put(KEY_reqName, reqInfo.getReqName());
		params.put(KEY_reqFullName, reqInfo.getReqFullName());
		params.put(KEY_revisionDate, reqInfo.getRevisionDate());
		params.put(KEY_reviewer, reqInfo.getReviewer());
		params.put(KEY_passTestVersion, ReqUtil.getPassTestVersion(reqInfo));

		params.put(KEY_callList, reqInfo.getCallInfos());
		params.put(KEY_bizDesc, ReqUtil.getBizDesc(reqInfo));
		params.put(KEY_designDesc, ReqUtil.getDesignDesc(reqInfo));
		params.put(KEY_testOverview, ReqUtil.getTestOverview(reqInfo));
		zipEntry = new ZipEntry(reqInfo.getEsbReqNo() + "_" + reqInfo.getReqFullName() + "_改造类设计说明书.doc");
		template = configuration.getTemplate("gaizaoleisheji_OESB.ftl");
		try {
			zip.putNextEntry(zipEntry);
			Writer writer = new OutputStreamWriter(zip);
			template.process(params, writer);
			zip.closeEntry();
		} catch (Exception e) {
			e.printStackTrace();
		}

		params = new HashMap<>();
		params.put(KEY_esbReqNo, reqInfo.getEsbReqNo());
		params.put(KEY_reqNo, reqInfo.getReqNo());
		params.put(KEY_reqName, reqInfo.getReqName());
		params.put(KEY_reqFullName, reqInfo.getReqFullName());
		params.put(KEY_evaluateDate, reqInfo.getEvaluateDate());
		params.put(KEY_reviewer, reqInfo.getReviewer());
		params.put(KEY_interfaceList, reqInfo.getInterfaceList());

		zipEntry = new ZipEntry(reqInfo.getEsbReqNo() + "_" + reqInfo.getReqFullName() + "_改造类需求估算表.xlsx");
		template = configuration.getTemplate("gusuanbiao_OESB.ftl");
		try {
			zip.putNextEntry(zipEntry);
			Writer writer = new OutputStreamWriter(zip);
			template.process(params, writer);
			zip.closeEntry();
		} catch (Exception e) {
			e.printStackTrace();
		}

		params.put(KEY_esbReqNo, reqInfo.getEsbReqNo());
		params.put(KEY_reqNo, reqInfo.getReqNo());
		params.put(KEY_reqName, reqInfo.getReqName());
		params.put(KEY_reqFullName, reqInfo.getReqFullName());
		params.put(KEY_revisionDate, reqInfo.getRevisionDate());
		params.put(KEY_reviewer, reqInfo.getReviewer());
		params.put(KEY_initTestVersion, ReqUtil.getInitTestVersion(reqInfo));
		params.put(KEY_verifyTestVersionList, ReqUtil.getVerifyTestVersionList(reqInfo));
		params.put(KEY_passTestVersion, ReqUtil.getPassTestVersion(reqInfo));
		params.put(KEY_sqlFile, reqInfo.getConfigFile().getSqlFile());

		params.put(KEY_testCycle, reqInfo.getTestCycle());
		params.put(KEY_tester, reqInfo.getTester());
		params.put(KEY_interfaceList, reqInfo.getInterfaceList());
		params.put(KEY_images, reqInfo.getScreenshots());
		params.put(KEY_testOverview, ReqUtil.getTestOverview(reqInfo));
		params.put(KEY_testRange, ReqUtil.getTestRange(reqInfo));

		zipEntry = new ZipEntry(reqInfo.getEsbReqNo() + "_" + reqInfo.getReqFullName() + "_改造类技术测试报告.doc");
		template = configuration.getTemplate("ceshibaogao_OESB.ftl");
		try {
			zip.putNextEntry(zipEntry);
			Writer writer = new OutputStreamWriter(zip);
			template.process(params, writer);
			zip.closeEntry();
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			zip.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			out.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		logger.info("生成文件成功！");
	}

	/**
	 *
	 * @param imgDir
	 * @param imageName
	 * @return
	 * @throws IOException
	 */
	public static String getImg(MultipartFile file) throws IOException {

		byte[] b = file.getBytes();
		return Base64.getEncoder().encodeToString(b);
	}

}
